﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class MenuInRoleController : BaseController
    {
        MenuInRoleBO menuInRoleBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MenuInRoleController));

        public ActionResult MenuInRole(MenuInRoleModel m = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (m == null) m = new MenuInRoleModel();

                SetActiveMenu("/MenuInRole/MenuInRole");
                m.RoleID = -1;
                var model = search(m, pageIndex, currentId, false);
                //ViewBag.lstRole = getListRole();
                ViewBag.lstApp = CommonData.getListApp("Chọn ứng dụng", "-1");
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Hiển thị form thêm mới chức năng
        [HttpPost]
        public ActionResult _MenuInRoleModel(int? id, int roleID, int appID)
        {
            try
            {
                MenuInRoleModel model = null;
                if (roleID > -1)
                {
                    if (id != null && id > -1)
                    {
                        menuInRoleBO = new MenuInRoleBO();
                        model = new MenuInRoleModel(menuInRoleBO.GetMenuInRoleById(id));
                    }

                    if (model == null)
                    {
                        model = new MenuInRoleModel()
                        {
                            MenuInRoleID = -1,
                            RoleID = roleID,
                            Descriptions = "",
                            IsActive = 1,
                            AppID = appID
                        };
                    }
                    ViewBag.lstRole = getListRole();
                    ViewBag.lstApp = CommonData.getListApp("Chọn ứng dụng", "-1");
                    ViewBag.lstMenu = getActiveMenuByAppID(getListMenuInRoleByRoleID(roleID, appID), appID);
                    ViewBag.lstMenuCon = getActiveMenuConByAppID(getListMenuInRoleByRoleID(roleID, appID), appID);
                    ViewBag.AppID = appID;
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView(model);
                    }
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(MenuInRoleModel aModel = null, int pageIndex = 0, string sort = "MenuInRoleId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (aModel == null) aModel = new MenuInRoleModel();
                
                var model = search(aModel, pageIndex, currentId, false);
                //ViewBag.lstRole = getListRole();
                return PartialView("~/Views/MenuInRole/_MenuInRoleList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Thêm mới chức năng
        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateMenuInRole(MenuInRoleModel model, int[] lstMenuID)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    menuInRoleBO = new MenuInRoleBO();
                    bool result = menuInRoleBO.createMenuInRole(model.toDALModel(), lstMenuID);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                           CommonData.AppName,
                           GetFunction(),
                           LogStream.GetJsonString<MenuInRoleModel>(model) +
                           "List menu id: " + CommonData.GetListId(lstMenuID),
                           Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateMenuInRole");

                        return Json(JsonResponse.Json200("Gán chức năng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(int[] id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    menuInRoleBO = new MenuInRoleBO();
                    bool result = menuInRoleBO.deleteMenuInRole(id);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(id),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa chức năng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<MenuInRoleModel> search(MenuInRoleModel myModel, int pageIndex, int currentId, bool compareEqual)
        {
            try
            {
                menuInRoleBO = new MenuInRoleBO();
                var models = new DataPage<MenuInRoleModel>();
                var DALModel = menuInRoleBO.GetDynamicListPaging(myModel.toDALModel(), PageSize, pageIndex, false);
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.MenuInRoleModel m in lstItem)
                {
                    models.Data.Add(new MenuInRoleModel(m));
                }

                MenuInRoleModel model = null;
                if (currentId >= 0 && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => user.MenuInRoleID == currentId);
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = myModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "MenuInRole",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "menu-in-role-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private List<MenuModel> getListMenuByAppID(int appId)
        {
            try
            {
                MenuBO menuBO = new MenuBO();
                var lstMenu = menuBO.GetAllMenuByAppId(appId);
                List<MenuModel> lstItems = new List<MenuModel>();
                foreach (var menu in lstMenu)
                {
                    lstItems.Add(new MenuModel(menu));
                }
                return lstItems;
            }
            catch
            {
                throw;
            }
        }


        //Get all menu in a role of database
        private Dictionary<int, string> getListMenuInRoleByRoleID(int roleID, int appID)
        {
            try
            {
                menuInRoleBO = new MenuInRoleBO();
                Dictionary<int, string> lstMenuApp = new Dictionary<int, string>();
                var lstItemsAppID = menuInRoleBO.GetListMenuInRoleByRoleID(roleID, appID);
                foreach (var menu in lstItemsAppID)
                {
                    Console.WriteLine(menu.MenuID);
                    lstMenuApp.Add(menu.MenuID, menu.MenuName);
                }
                return lstMenuApp;
            }
            catch
            {
                throw;
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetListMenu(int appID, int roleID)
        {
            try
            {
                var menus = getActiveMenuByAppID(getListMenuInRoleByRoleID(roleID, -1), appID);
                return Json(menus, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getActiveMenuByAppID(Dictionary<int, string> lstMenuInRole, int appID)
        {
            try
            {
                List<MenuModel> lstMenu = getListMenuByAppID(appID);
                List<SelectListItem> lstItems = new List<SelectListItem>();
                foreach (var menu in lstMenu)
                {
                    if (!lstMenuInRole.ContainsKey(menu.MenuId) && menu.MenuUrl == "#")
                    //if (!lstMenuInRole.ContainsKey(menu.MenuId))
                    {
                        lstItems.Add(new SelectListItem
                        {
                            Value = menu.MenuId.ToString(),
                            Text = menu.MenuName
                        });
                    }
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch
            {
                throw;
            }
        }

        private IEnumerable<SelectListItem> getActiveMenuConByAppID(Dictionary<int, string> lstMenuInRole, int appID)
        {
            try
            {
                List<MenuModel> lstMenu = getListMenuByAppID(appID);
                List<SelectListItem> lstItems = new List<SelectListItem>();
                foreach (var menu in lstMenu)
                {
                    if (!lstMenuInRole.ContainsKey(menu.MenuId) && menu.MenuUrl != "#")
                    {
                        lstItems.Add(new SelectListItem
                        {
                            Value = menu.MenuId.ToString(),
                            Text = menu.MenuName
                        });
                    }
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch
            {
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListApp()
        {
            try
            {
                ApplicationBO appBO = new ApplicationBO();
                var lstType = appBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "-1",
                    Text = "Chọn ứng dụng"
                });
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.AppId.ToString(),
                        Text = String.Concat(type.AppName, " - ", type.AppCode)
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListRole()
        {
            try
            {
                RoleBO roleBO = new RoleBO();
                var lstType = roleBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                if (lstType.Any())
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = "-1",
                        Text = "Chọn vai trò"
                    });

                    foreach (var type in lstType)
                    {
                        lstItems.Add(new SelectListItem
                        {
                            Value = type.RoleId.ToString(),
                            Text = type.RoleName
                        });
                    }
                }
                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public JsonResult GetListRoleByApp(int AppId)
        {
            try
            {
                RoleBO roleBO = new RoleBO();
                var lstType = roleBO.GetListRoleByApp(AppId);
                List<SelectListItem> lstItems = new List<SelectListItem>();
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.RoleId.ToString(),
                        Text = type.RoleName
                    });
                }

                return Json(new SelectList(lstItems, "Value", "Text"));
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public ActionResult reloadParentMenu(int appId, int roleID)
        {
            try
            {
                ViewBag.lstMenu = getActiveMenuByAppID(getListMenuInRoleByRoleID(roleID, -1), appId);
                ViewBag.AppID = appId;
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/MenuInRole/_ListMenu.cshtml");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private string GetFunction()
        {
            return "Phân chức năng cho vai trò - MenuInRoleController";
        }
    }
}